<template>
  <el-button-group>
    <el-upload
      ref="upload"
      class="upload-demo"
      action="/api/oem/v1/Configs/Configuration"
      :headers="{ 'Content-Type': 'application/octet-stream' }"
      :limit="1"
      :on-exceed="handleExceed"
    >
      <el-button type="info">
        {{ $t('pageConfigureManagement.button.import') }}
      </el-button>
    </el-upload>

    <el-button type="primary" @click="confirmDownload">
      {{ $t('pageConfigureManagement.button.download') }}
    </el-button>
  </el-button-group>
  <el-progress v-if="downloading" :percentage="100">
    <el-button text>
      {{ $t('pageConfigureManagement.modal.downloadPrepareTitle') }}
    </el-button>
  </el-progress>
  <el-tabs v-model="activeName" class="demo-tabs">
    <el-tab-pane
      :label="$t('pageConfigureManagement.tabs.tab1.name')"
      name="first"
    >
      <el-table :data="tableData" height="500" style="width: 100%">
        <el-table-column
          prop="Name"
          :label="$t('pageConfigureManagement.tabs.tab1.fields.name')"
          width="180"
        />
        <el-table-column
          prop="CriticalLow"
          :label="$t('pageConfigureManagement.tabs.tab1.fields.criticalLow')"
          width="180"
        >
          <template #default="scope">
            <div v-if="scope.row.CriticalLow != undefined">
              <el-icon
                class="cursor-pointer"
                @click="modify(scope.row, 'CriticalLow')"
                ><edit
              /></el-icon>
              {{ scope.row.CriticalLow + unitFormatter(scope.row.Unit) }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="WarningLow"
          :label="$t('pageConfigureManagement.tabs.tab1.fields.warningLow')"
        >
          <template #default="scope">
            <div v-if="scope.row.WarningLow != undefined">
              <el-icon
                class="cursor-pointer"
                @click="modify(scope.row, 'WarningLow')"
                ><edit
              /></el-icon>
              {{ scope.row.WarningLow + unitFormatter(scope.row.Unit) }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="WarningHigh"
          :label="$t('pageConfigureManagement.tabs.tab1.fields.WarningHigh')"
        >
          <template #default="scope">
            <div v-if="scope.row.WarningHigh != undefined">
              <el-icon
                class="cursor-pointer"
                @click="modify(scope.row, 'WarningHigh')"
                ><edit
              /></el-icon>
              {{ scope.row.WarningHigh + unitFormatter(scope.row.Unit) }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="CriticalHigh"
          :label="$t('pageConfigureManagement.tabs.tab1.fields.criticalHigh')"
        >
          <template #default="scope">
            <div v-if="scope.row.CriticalHigh != undefined">
              <el-icon
                class="cursor-pointer"
                @click="modify(scope.row, 'CriticalHigh')"
                ><edit
              /></el-icon>
              {{ scope.row.CriticalHigh + unitFormatter(scope.row.Unit) }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { genFileId } from 'element-plus';
import type { UploadProps, UploadRawFile } from 'element-plus';
import { useConfigureStore } from '@/store/Settings/ConfigureManagement';
import { Edit } from '@element-plus/icons-vue';

const configureStore = useConfigureStore();
const i18n = useI18n();

const upload = ref();
const downloading = ref(false);

const activeName = ref('first');

await configureStore.getConfigures();
const tableData = computed(() => configureStore.sensorInfo);

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const confirmDownload = () => {
  ElMessageBox.confirm(
    i18n.t('pageConfigureManagement.modal.confirmMessage1'),
    i18n.t('pageConfigureManagement.modal.confirmTitle1'),
    {
      confirmButtonText: i18n.t('global.action.confirm'),
      cancelButtonText: i18n.t('global.action.cancel'),
    },
  ).then(() => {
    downloading.value = true;
    configureStore
      .download()
      .then(() => {
        ElMessage({
          type: 'success',
          message: i18n.t('pageConfigureManagement.modal.successDownload'),
        });
      })
      .catch(() => {
        ElMessage({
          type: 'error',
          message: i18n.t('pageConfigureManagement.modal.errorDownload'),
        });
      })
      .finally(() => {
        downloading.value = false;
        configureStore.getConfigures();
      });
  });
};

const unitFormatter = (string: any) => {
  switch (string) {
    case 'DegreesC':
      return '°C';
    case 'RPMS':
      return 'RPM';
    case 'Volts':
      return 'V';
    case 'Metters':
      return 'M';
    case 'Amperes':
      return 'A';
    case 'Joules':
      return 'J';
    case 'CFM':
      return 'CFM';
    case 'Pascals':
      return 'P';
    case 'Percent':
      return '%';
    case 'Watts':
      return 'W';
    default:
      return string;
  }
};

const diffList = [] as any;

const modify = (row: { [index: string]: any }, field: string) => {
  const diffRow = Object.assign({}, row);
  ElMessageBox.prompt(
    i18n.t('pageConfigureManagement.inputValue'),
    i18n.t('pageConfigureManagement.tip'),
    {
      confirmButtonText: i18n.t('global.action.confirm'),
      cancelButtonText: i18n.t('global.action.cancel'),
      inputErrorMessage: 'Invalid Format',
    },
  )
    .then(async ({ value }) => {
      diffRow[field] = +value;
      diffList.push(diffRow);
      await configureStore
        .UpdateSensorConfigure(diffList)
        .then(() => {
          ElMessage({
            type: 'success',
            message: i18n.t(
              'pageConfigureManagement.tabs.tab1.toast.successUpdate',
            ),
          });
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: i18n.t(
              'pageConfigureManagement.tabs.tab1.modal.errorUpdate',
            ),
          });
        })
        .finally(() => {
          configureStore.getConfigures();
        });
    })
    .catch(() => {});
};
</script>
